<template>
  <div class="banner">
    <div class="bg" :style="{ backgroundImage: `url(${curFilm?.poster})` }"></div>
    <div class="swiper">
      <div class="swiper-wrapper">
        <div
          class="swiper-slide"
          v-for="item in filmList"
          :key="item.filmId"
          @click="onClick(item)"
        >
          <img :src="item.poster" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Swiper from 'swiper'
import 'swiper/css'

const props = defineProps<{
  filmList: IFilm[]
  filmId: Number
}>()

const emit = defineEmits(['change'])

// 当前选择的电影对象
const curFilm = computed(() => props.filmList.find((item) => item.filmId === props.filmId))

function onClick(item: IFilm) {
  emit('change', item)
}

watch(
  () => props.filmList,
  (newVal) => {
    var mySwiper = new Swiper('.swiper', {
      slidesPerView: 4, // 一个屏幕展示多少个 slide
      spaceBetween: 16, // slide 间的间隔
      centeredSlides: true, // 当前激活的 slide 居中
      slideToClickedSlide: true // 点击某个 slide 激活它
    })

    // 计算出 index
    const index = newVal.findIndex((item) => item.filmId === props.filmId)
    setTimeout(() => {
      // 切换到 index 下标的 slide 上
      mySwiper.slideTo(index, 1000)
    }, 30)

    // 监听 mySwiper 事件
    // mySwiper.on('slideChange', (...rest) => {
    //   console.log('slideChange', rest)
    // })
  },
  {
    flush: 'post'
  }
)
</script>

<style scoped>
.banner {
  height: 160px;
  color: #fff;
  padding: 15px 0;
  position: relative;
  overflow: hidden;
}

.bg {
  position: absolute;

  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  filter: blur(30px);
}

.swiper {
  width: 100%;
  height: 160px;
}

.swiper-slide {
  display: flex;
  align-items: flex-end;
  width: 72px !important;
}
.swiper-slide-active {
  width: 90px !important;
}

.swiper-slide img {
  display: block;
  width: 100%;
  height: 104px;
  transition: all 0.5s ease;
}

.swiper-slide-active img {
  display: block;
  width: 100%;
  height: 130px;
}
</style>
